import 'dart:convert';
import 'dart:io';

import 'package:dart_date/dart_date.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';
import 'package:flutter_echarts/flutter_echarts.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:visibility_detector/visibility_detector.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/devices/device_tab/model/device_item_model.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/constants/time_formated.dart';
import 'package:yt_devops/utils/func_utils.dart';

class DeviceDataHistoryChart extends StatefulWidget {
  final double height;
  final int deviceId;
  // 属性值的物模型
  final Map property;
  final double? amount;

  final String? dataItemName;
  const DeviceDataHistoryChart(
      {super.key,
      this.height = 331,
      required this.deviceId,
      required this.amount,
      required this.property,
      this.dataItemName});

  @override
  State<DeviceDataHistoryChart> createState() => _DeviceDataHistoryChartState();
}

class _DeviceDataHistoryChartState extends State<DeviceDataHistoryChart> {
  DeviceServices services = DeviceServices();

  late String startTime;
  late String? endTime;

  List seriseData = [];

  bool isLoad = true;

  dynamic _webController;
  bool _isVisible = false;

  @override
  void initState() {
    startTime = DateTime.now().startOfDay.format(TimeFormated.dateTimeFromated);
    endTime = DateTime.now().endOfDay.format(TimeFormated.dateTimeFromated);
    super.initState();
    getHistoryData();
  }

  @override
  void didUpdateWidget(covariant DeviceDataHistoryChart oldWidget) {
    getHistoryData();
    super.didUpdateWidget(oldWidget);
  }

  String get chartName => FuncUtils.iszhCN()
      ? '${widget.property['name']}${ResKey.statistics.tr}'
      : '${widget.property['name']} ${ResKey.statistics.tr}';

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.fromLTRB(0, 15.h, 0, 6.h),
            child: Text(
              chartName,
              style: TextStyles.f18.boldStyle,
            ),
          ),
          Text(
            widget.property['name'],
            style: TextStyles.f12.copyWith(height: 1.2),
          ),
          Text.rich(TextSpan(
              text: widget.amount != null
                  ? widget.amount!.toStringAsFixed(2)
                  : '--',
              style: TextStyles.f20.mediumStyle.copyWith(
                height: 1.5,
                fontFamily: 'DIN',
              ),
              children: [
                const TextSpan(text: ' '),
                TextSpan(text: getUnit(), style: TextStyles.lf11)
              ])),
          Container(
            padding: EdgeInsets.symmetric(vertical: 16.w),
            height: widget.height,
            child: VisibilityDetector(
              key: UniqueKey(),
              onVisibilityChanged: onVisibilityChanged,
              child: SizedBox(
                height: widget.height,
                child: Echarts(
                  captureAllGestures: true,
                  onLoad: (p0) {
                    _webController = p0;
                  },
                  option: '''
               { 
                grid: {
                  top: 30,
                  bottom: 24,
                  right: 16,
                },
                legend:{
                  show:true,
                  icon:'rect',
                  itemWidth:12,
                  itemHeight:3,
                  right:16,
                  itemStyle:{
                    borderCap:'round'
                  }
                   
                  
                },
                tooltip: {
                  trigger: 'axis',
                  
                },
                xAxis: {
                  type: 'category',
                
                 
                },
                yAxis: {
                  type: 'value',
                  name: '${getUnit()}',
                  axisLine:{
                    show:true,
                    lineStyle: {
                      color:'#999999',
                      type:'dashed'
                    }
                  },
                  splitLine:{
                    show:true,
                    lineStyle:{
                      color:'rgba(0, 0, 0, 0.09)'
                    }
                  }
                },
                xAxis: {
                  type: 'category',
                  minInterval:15,
                  alignWithLabel: true,
                  axisLine:{
                    show:true,
                    lineStyle: {
                      color:'#999999',
                      type:'dashed'
                    }
                  },
                  
                    
                },
                dataZoom: [
                  {
                    type: 'inside',
                    show:true,
                  },
                 
                ],

                series: {
                  type: 'line',
                  name:'${widget.dataItemName}',
                  itemStyle: {
                    'color': 'rgba(24, 144, 255, 1)',
                  
                  },
                  areaStyle: {
                    'color': {
                      'type': 'linear',
                      'x': 0,
                      'y': 0,
                      'x2': 0,
                      'y2': 1,
                      'colorStops': [
                        {
                          'offset': 0,
                          'color':'rgba(24, 144, 255, 0.23)'  // 0% 处的颜色
                        },
                        {
                          'offset': 1,
                          'color': 'rgba(255, 255, 255, 0.23)' // 100% 处的颜色
                        }
                      ],
                    }
                  },
                  data:${jsonEncode(seriseData)}
                  
                }
               
              }
              ''',
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  onVisibilityChanged(VisibilityInfo info) {
    if (Platform.isIOS) {
      if (!isLoad && info.visibleFraction > 0.2) {
        isLoad = true;
      } else if (info.visibleFraction > 0) {
        isLoad = true;
      }
    }
  }

  getHistoryData() => Configs.httpClient.requestWithLoading(() async {
        var param = {
          'deviceId': widget.deviceId,
          'key': widget.property['id'],
          'startTime': startTime,
          'endTime': endTime,
          'msgType': 1
        };
        var data = await services.getDeviceDataForHistoryList(param);
        if (data != null) {
          String dataType = widget.property['dataType']['type'] ?? 'double';
          String dataTypeKey = '${dataType}Val';
          seriseData.clear();
          for (var item in data) {
            var value =
                double.parse(item[dataTypeKey].toString()).toStringAsFixed(2);
            var time = getHourAndMinute(item['eventTs']);

            seriseData.add([time, value]);
          }
        }
        if (mounted) {
          setState(() {});
        }
      }, showLoading: false);

  String getUnit() {
    return widget.property['dataType']?['specs']?['unit'] ?? '';
  }

  String getHourAndMinute(String? eventTs) {
    if (eventTs == null) {
      return '';
    } else {
      return eventTs.substring(11);
    }
  }
}
